//
//  WQUserAccountModel.swift
//  WeiBo
//
//  Created by 张德华 on 7/24/16.
//  Copyright © 2016 ZhangDeHua. All rights reserved.
//

import UIKit

private let WQWeiboUserAccountKey = "wq.zhang"


class WQUserAccountModel: NSObject {

    ///------ 用户账户单例,全局入口
    static let sharedUserAccount: WQUserAccountModel = WQUserAccountModel()
    
    ///------ 用户登录标记
    var isLogin:Bool {
        return access_token != nil
        
    }
    
    /**用户授权的唯一票据，用于调用微博的开放接口*/
    var access_token: String?
    /**access_token的生命周期，单位是秒数*/
    var expires_in: NSTimeInterval = 0 {
        didSet{
            expires_Date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }

    
    /**用户昵称*/
    var screen_name: String?
    /**用户头像地址（大图），180×180像素*/
    var avatar_large: String?
    
    /**过期日期*/
    var expires_Date: NSDate?
    /**需要查询的用户ID*/
    var uid: String?
    
    
    private override init() {
        super.init()
        
        loadUserAccount()
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    
    }

    ///------ 重写description
    override var description: String {
        
        let keys = ["screen_name","avatar_large","access_token","expires_in","expiresDate","uid"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    
    
    ///------ kvc 重载构造函数
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
}



extension WQUserAccountModel {
    
    func updateUserAccount(dict: [String: AnyObject]){
        setValuesForKeysWithDictionary(dict)
        saveUserAccount()
    }
    
    private func saveUserAccount() {
        
        let keys = ["screen_name","avatar_large","access_token","expiresDate","uid"]
        let dict = dictionaryWithValuesForKeys(keys)
        
        ///------ 字典存入偏好
        NSUserDefaults.standardUserDefaults().setObject(dict, forKey: WQWeiboUserAccountKey)
        print(NSHomeDirectory())
    }
    
    
    private func loadUserAccount() {
        
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(WQWeiboUserAccountKey) as? [String: AnyObject] else {
            
            return
        }
        
        setValuesForKeysWithDictionary(dict)
        
        if isExpired{
            print("token 已经过期")
            access_token = nil
        } else{
            print("token 正常")
        }
    }
    
    
    // MARK: - ************判断是否过期
    private var isExpired: Bool {
        
        return expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedAscending
    }
    
    
    
}


